#!/usr/bin/env python

import pygtk
pygtk.require('2.0')

import sys, os
import time
import gtk, gnomeapplet, gobject

import xmmsclient

class XMMS2Control:
    def __init__(self, applet, iid):
	self.__applet = applet
	self.__iid = iid

	self.__connected = False
	self.xmms_connect()

	self.__hbox = gtk.HBox()
	self.__main_button = gtk.Button("XMMS2:")
	self.__main_button.set_relief(gtk.RELIEF_NONE)
	self.__main_button.connect("clicked", self.main_button_clicked)
	self.__hbox.add(self.__main_button)

	self.__prev = self.__build_button("previous")
	self.__prev.connect("clicked", self.previous_clicked)
	self.__hbox.add(self.__prev)

	self.__play_button = self.__build_button("play")
	self.__play_button.connect("clicked", self.toggleplay_clicked)
	self.__hbox.add(self.__play_button)

	self.__next = self.__build_button("next")
	self.__next.connect("clicked", self.next_clicked)
	self.__hbox.add(self.__next)

	self.__update_play_status()
	self.__timeout_interval = 500
	gobject.timeout_add(self.__timeout_interval, self.timeout_callback)

	self.__applet.add(self.__hbox)
	self.__applet.show_all()

    def __is_connected(self):
	# TODO: fazer um teste decente e deprecar variavele self.__connected
	return self.__connected == True

    def xmms_connect(self):
	# connect to XMMS2...
	self.__xmms = xmmsclient.XMMS("XMMS2Control")
	try:
	    self.__xmms.connect(os.getenv("XMMS_PATH"))
	    self.__connected = True
	except IOError, detail:
	    res = self.__message_dialog(
		    u"<b>XMMS2 Control Applet:</b> %s\nPlease, make sure you have xmms2d running, then click OK!" % detail)
	    if not res:
		sys.exit(1)
	    else:
		# tenta reconectar
		self.xmms_connect()

    def __message_dialog(self, message):
	dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING)
	dialog.set_title("XMMS2 Control Applet")
	dialog.set_markup(message)

	# Cancel and OK
	dialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
	dialog.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)

	response = dialog.run()
	dialog.destroy()
	return response == gtk.RESPONSE_OK
    
    def __build_button(self, type):
	button = gtk.Button("")
	image = gtk.Image()
	image.set_from_stock("gtk-media-" + type, gtk.ICON_SIZE_BUTTON)
	button.set_relief(gtk.RELIEF_NONE)
	button.set_image(image)
	return button

    def timeout_callback(self):
	self.__update_play_status()
	# call me back, please!
	return 1

    def __update_play_status(self):
	icon_type = "gtk-media-play"
	if self.__playing():
	    icon_type = "gtk-media-pause"
	image = gtk.Image()
	image.set_from_stock(icon_type, gtk.ICON_SIZE_BUTTON)
	self.__play_button.set_image(image)

    def __playing(self):
	if not self.__is_connected(): return False
	result = self.__xmms.playback_status()
	# TODO: test for error
	result.wait()
	return result.value() == xmmsclient.PLAYBACK_STATUS_PLAY

    def main_button_clicked(self, event):
	if not self.__is_connected(): return False
	allowed=['*.ogg', '*.mp3']
	uris = self.dialog_open('Add Songs:',
		patterns=allowed,
		folder='/home/eljunior/Music') # TODO: get from config
	if not uris: return
	for uri in uris:
	    self.__xmms.playlist_add_url(uri).wait()

    def dialog_open(self, title='', parent=None, patterns=[], folder=None):
	"""Displays an open dialog and return URIs."""
	filechooser = gtk.FileChooserDialog(title or _('Open'),
		parent, gtk.FILE_CHOOSER_ACTION_OPEN,
		(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
		    gtk.STOCK_OPEN, gtk.RESPONSE_OK))
	filechooser.set_select_multiple(True)

	if patterns:
	    file_filter = gtk.FileFilter()
	    for pattern in patterns:
		file_filter.add_pattern(pattern)
	    filechooser.set_filter(file_filter)
	filechooser.set_default_response(gtk.RESPONSE_OK)

	if folder:
	    filechooser.set_current_folder(folder)

	response = filechooser.run()
	if response != gtk.RESPONSE_OK:
	    filechooser.destroy()
	    return None

	uris = filechooser.get_uris()
	filechooser.destroy()
	return uris

    def previous_clicked(self, event):
	if not self.__is_connected(): return False
	result = self.__xmms.playlist_current_pos()
	result.wait()
	position = result.value()['position']
	if position > 0:
	    position -= 1
	self.__xmms.playlist_set_next(position).wait()
	self.__xmms.playback_tickle().wait()

    def toggleplay_clicked(self, event):
	if not self.__is_connected(): return False
	if self.__playing():
	    self.__xmms.playback_pause().wait()
	else:
	    self.__xmms.playback_start().wait()
	self.__update_play_status()

    def next_clicked(self, event):
	if not self.__is_connected(): return False
	result = self.__xmms.playlist_current_pos()
	result.wait()
	position = result.value()['position']
	position += 1
	self.__xmms.playlist_set_next(position).wait()
	self.__xmms.playback_tickle().wait()


def sample_factory(applet, iid):
    XMMS2Control(applet, iid)
    return gtk.TRUE

# for debugging:
if len(sys.argv) == 2 and sys.argv[1] == "run-in-window":
    main_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    main_window.set_title("XMMS2 Control Python Applet")
    main_window.connect("destroy", gtk.main_quit)
    app = gnomeapplet.Applet()
    sample_factory(app, None)
    app.reparent(main_window)
    main_window.show_all()
    gtk.main()
    sys.exit()

gnomeapplet.bonobo_factory("OAFIID:GNOME_XMMS2ControlApplet_Factory",
	gnomeapplet.Applet.__gtype__,
	"simple XMMS2 control", "1.0", sample_factory)
